<template>
  <div id="app">
    <!-- head -->
    <HeadViewVue @addItem=addItem> </HeadViewVue>
    <ListViewVue v-if="todoList.length != 0" :todoList="todoList">
    </ListViewVue>

    <!-- selectAll deleteFinish -->
    <FootViewVue v-if="todoList.length != 0" :todoList="todoList" @selectAll=selectAll @deleteFinish=deleteFinish>
    </FootViewVue>
  </div>
</template>

<script>
import FootViewVue from "./components/FootView.vue";
import HeadViewVue from "./components/HeadView.vue";
import ListViewVue from "./components/ListView.vue";
export default {
  name: "App",

  data() {
    return {
      todoList: JSON.parse(localStorage.getItem("todoList")) || []
    };
  },

  watch: {
    todoList: {
      deep: true,
      handler() {
        localStorage.setItem("todoList", JSON.stringify(this.todoList))
      }
    }
  },
  mounted() {
    //在挂载完成的时候绑定全局事件
    this.$bus.$on('deleteTodo', this.deleteTodo)
    this.$bus.$on('finishTodo', this.finishTodo)
  },
  beforeDestroy() {
    //在即将销毁时解绑全局事件
    this.$bus.$off(['deleteTodo', 'finishTodo'])
  },
  methods: {
    addDefData() {
      const todoList = [
        { id: "001", content: "抽烟", done: false },
        { id: "002", content: "喝酒", done: true },
        { id: "003", content: "嚼槟榔", done: false },
      ]
      localStorage.setItem("todoList", JSON.stringify(todoList))
    },

    //添加一个todo
    addItem(todo) {

      this.todoList.unshift(todo);
    },
    //勾选完成or未完成
    finishTodo(id) {
      this.todoList.forEach((todo) => {
        if (todo.id === id) {
          todo.done = !todo.done;
          return;
        }
      });
    },
    //删除一个todo ...arr接收多个参数,arr 类型为数组
    deleteTodo(id, ...arr) {
      console.log(id, arr instanceof Array)
      this.todoList = this.todoList.filter((todo) => {
        return todo.id != id;
      });
    },
    //全选
    selectAll(isAll) {
      console.log("selectAll")
      this.todoList.forEach((todo) => {
        todo.done = isAll;
      });
    },
    //删除已完成
    deleteFinish() {
      this.todoList = this.todoList.filter((todo) => !todo.done);
    },
  },
  components: {
    HeadViewVue,
    ListViewVue,
    FootViewVue,
  },
};
</script>

<style scoped lang="less">
#app {
  width: 500px;
  padding: 20px;
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 5px;
}
</style>
